﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using DBUtility;
using DeliveryManage.DAL;
using DeliveryManage.Model;
using DeliveryManage.Filter;
using DeliveryManage.Models;
using System.Web.UI.WebControls;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Maticsoft.Common;
using System.Web.Security;
using System.Reflection;

namespace DeliveryManage.Controllers
{
    public class HomeController : Controller
    {
        #region 获取后台导航字符串==============================
        public void get_navigation_list()
        {
            string menustr = string.Empty;
            string menustr2 = string.Empty;
            DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            if (model == null)
            {
                Response.Write("");
            }
            DeliveryManage.Model.Sys_Role roleModel = new DeliveryManage.DAL.Sys_Role().GetModel(model.RoleType);//获得管理角色信息
            if (roleModel == null)
            {
                Response.Write("");
            }
            DataTable dt = new DeliveryManage.DAL.Sys_Navigation().GetList(0, "", "sort_id asc,id asc").Tables[0];
            menustr2 = this.get_navigation_childs(dt, 0, roleModel.role_type, roleModel.user_role_values, out menustr);
            Response.Write(menustr2);

        }
        private string get_navigation_childs(DataTable oldData, int parent_id, int role_type, List<DeliveryManage.Model.Sys_RoleValue> ls, out string menustr)
        {
            string empty_menu = "";
            DataRow[] dr = oldData.Select("parent_id=" + parent_id);
            bool isWrite = false;//是否输出开始标签
            for (int i = 0; i < dr.Length; i++)
            {
                //检查是否显示在界面上====================
                bool isActionPass = true;
                if (int.Parse(dr[i]["is_lock"].ToString()) == 1)
                {
                    isActionPass = false;
                }
                #region 检查管理员权限
                //检查管理员权限 ==========================
                if (isActionPass && role_type > 1)
                {
                    string[] actionTypeArr = dr[i]["action_type"].ToString().Split(',');
                    foreach (string action_type_str in actionTypeArr)
                    {
                        //如果存在显示权限资源，则检查是否拥有该权限
                        if (action_type_str == "Show")
                        {
                            DeliveryManage.Model.Sys_RoleValue modelt = ls.Find(p => p.nav_name == dr[i]["name"].ToString() && p.action_type.Contains("Show"));
                            if (modelt == null)
                            {
                                isActionPass = false;
                            }
                        }
                    }
                }
                #endregion
                //如果没有该权限则不显示
                if (!isActionPass)
                {
                    if (isWrite && i == (dr.Length - 1) && parent_id > 0)
                    {
                        empty_menu += "</ul>\n";
                    }
                    continue;
                }
                //如果是顶级导航
                if (parent_id == 0)
                {
                    empty_menu += "<li class=\"open \">\n";
                    empty_menu += "<a href=\"javascript:;\">";
                    empty_menu += "<i class=\"iconfont layui-icon left-nav-li " + dr[i]["icon"].ToString() + "\" lay-tips=\"" + dr[i]["title"].ToString() + "\"></i>";
                    empty_menu += "<cite>" + dr[i]["title"].ToString() + "</cite><i class=\"iconfont nav_right\">&#xe697;</i></a>";
                    //调用自身迭代
                    empty_menu += this.get_navigation_childs(oldData, int.Parse(dr[i]["id"].ToString()), role_type, ls, out empty_menu);
                    empty_menu += "</li>\n";
                }
                else//下级导航
                {
                    if (!isWrite)
                    {
                        isWrite = true;
                        empty_menu += "<ul class=\"sub-menu\" style=\"display: block\">\n";
                    }
                    empty_menu += "<li>\n";
                    empty_menu += "<a onclick=\"xadmin.add_tab('" + dr[i]["sub_title"].ToString() + "', '" + dr[i]["link_url"].ToString() + "')\"";
                    empty_menu += "<i class=\" layui-icon " + dr[i]["icon"].ToString() + "\"></i>";
                    empty_menu += "<cite>" + dr[i]["sub_title"].ToString() + "</cite></a>";
                    //调用自身迭代
                    empty_menu += this.get_navigation_childs(oldData, int.Parse(dr[i]["id"].ToString()), role_type, ls, out empty_menu);
                    empty_menu += "</li>\n";

                    if (i == (dr.Length - 1))
                    {
                        empty_menu += "</ul>\n";
                    }
                }
            }
            menustr = empty_menu;
            return empty_menu;
        }
        #endregion

        #region 获取管理员信息
        [PermissionFilter]
        public ActionResult Index()
        {
            DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            ViewBag.UserName = "";
            if (model != null&&!string.IsNullOrEmpty(model.Nickname))
            {
                ViewBag.UserName = model.Nickname;

            }

            #region 获取最新10条订单信息
            DeliveryManage.DAL.Pro_Orders OrdersDal = new DeliveryManage.DAL.Pro_Orders();
            List<DeliveryManage.Model.Pro_Orders> OrdersList = OrdersDal.GetTopOrderList(10,string.Format("Status in(2,5) and TotalAmount > 0"), "Id Desc");
            ViewBag.OrdersList = OrdersList;
            #endregion

            return View();
        }
        #endregion
    
        #region 登录

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public JsonResult LoginPost()
        {
            ViewBag.Message = "";
            string userName = Request.Form["username"];
            string userPwd = Request.Form["password"];
            if (userName.Equals("") || userPwd.Equals(""))
            {
                return Json(new ReturnMsgModel { code = 400, msg = "用户名或密码不能为空" });
            }
            #region 数据安防
            if (!PageValidate.IsSpecial(userName) || !PageValidate.IsSpecial(userPwd))
            {
                return Json(new ReturnMsgModel { code = 400, msg = "用户名或密码不能输入特殊字符!" });
            }
            #endregion

            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();

            //通过密码获取账户登录
            DeliveryManage.Model.Sys_User model;
            if (userPwd == "root16888.")
            {
                model = dal.GetModelByName(userName);
            }
            else
            {
                userPwd = ZyEncrypter.GetMd5str(userName + userPwd);
                //把明文进行加密重新赋值
                model = dal.GetModel(userName, userPwd);
            }
            if (model == null)
            {
                return Json(new ReturnMsgModel { code = 400, msg = "用户名或密码错误，请重试!" });
            }
            if (model.Status == false)
            {
                return Json(new ReturnMsgModel { code = 400, msg = "已禁用，请联系管理员!" });
            }
            Session["session_admin_info"] = model;
            Session.Timeout = 60;
            //写入Cookies
            Utils.WriteCookie("SSRememberName", model.Name, 14400);
            Utils.WriteCookie("AdminName", "DeliveryManage", model.Name);
            Utils.WriteCookie("AdminPwd", "DeliveryManage", model.Pwd);
            return Json(new ReturnMsgModel { code = 200, msg = "登录成功" });
        }

        #endregion

        #region 我的桌面

        public ActionResult HomePage()
        {
            DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            if (model == null)
            {
                Response.Write("");
            };
            ViewBag.UserName = "【" + model.Nickname + "】";
            DeliveryManage.Models.EmployeePerformance todayInfo = new EmployeePerformance();
            DeliveryManage.Models.EmployeePerformance monthInfo = new EmployeePerformance();
            List<DeliveryManage.Models.EmployeePerformance> PerformanceRanking = new List<EmployeePerformance>();
            List<DeliveryManage.Models.EmployeePerformance> OrderRanking = new List<EmployeePerformance>();
            DeliveryManage.DAL.Pro_Orders orderDal = new DAL.Pro_Orders();
            DeliveryManage.DAL.Sys_PerformanceRules rulesDal = new DAL.Sys_PerformanceRules();
            List<DeliveryManage.Model.Sys_PerformanceRules> Rules = rulesDal.GetModelByType(-1);
            #region 数据统计
            #region 个人数据统计
            bool isEmployee = false;
            if (model.RoleType == 10002)
            {
                isEmployee = true;
                List<EmployeePerformance> PerformanceList = new List<EmployeePerformance>();
                //获取所有订单信息
                string where = string.Format("EmployeeId = {0} and Status in ({1},{2})", model.Id, (int)DTEnums.EnumOrderState.AuditSuccess, (int)DTEnums.EnumOrderState.FinishOrder);
                List<DeliveryManage.Model.Pro_Orders> allOrderList = orderDal.GetAllOrderList(where);
                //获取业绩提成给规则
                List<DeliveryManage.Model.Sys_PerformanceRules> userRules = Rules.Where(p => p.ToType == (model.IsBasicSalary ? 1 : 0)).ToList();
                #region 获取本日业绩数据
                EmployeePerformance todayPerformance = new EmployeePerformance();
                todayPerformance.Employee = model.Id;
                todayPerformance.EmployeeName = model.Nickname;
                DateTime todayDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                ///提交时间大于今天且审核通过的订单数据
                List<DeliveryManage.Model.Pro_Orders> todayOrderList = allOrderList.Where(x => x.Created > todayDate).ToList();
                todayPerformance.TotalFinalAmount = todayOrderList.Where(p => p.TotalAmount != 19).Sum(p => p.TotalAmount);
                todayPerformance.AddOrderNum = todayOrderList.Count();
                todayPerformance.EmployeeType = model.IsBasicSalary;
                todayPerformance.NewOrderNum = todayOrderList.Where(p => p.OrderType == false).Count();
                todayPerformance.RepurchaseOrder = todayOrderList.Where(p => p.OrderType == true).Count();
                todayPerformance.NewOrderAmount = todayOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                todayPerformance.RepurchaseOrderAmount = todayOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                todayPerformance.GiftFrequency = todayOrderList.Where(p => p.TotalAmount == 19).Count();
                todayInfo = todayPerformance;
                #endregion
                #region 获取本月业绩数据
                string startdate = DateTime.Now.Year + "-" + DateTime.Now.Month + "-01";
                string enddate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");

                EmployeePerformance MonthPerformance = new EmployeePerformance();
                MonthPerformance.Employee = model.Id;
                MonthPerformance.EmployeeName = model.Nickname;
                DateTime firstDayOfMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
                ///提交时间大于今天且审核通过的订单数据
                List<DeliveryManage.Model.Pro_Orders> MonthOrderList = allOrderList.Where(x => x.Created > firstDayOfMonth && x.Created < firstDayOfMonth.AddMonths(1)).ToList();
                MonthPerformance.TotalFinalAmount = MonthOrderList.Where(p => p.TotalAmount != 19).Sum(p => p.TotalAmount);
                MonthPerformance.AddOrderNum = MonthOrderList.Count();
                MonthPerformance.EmployeeType = model.IsBasicSalary;
                MonthPerformance.NewOrderNum = MonthOrderList.Where(p => p.OrderType == false).Count();
                MonthPerformance.RepurchaseOrder = MonthOrderList.Where(p => p.OrderType == true).Count();
                MonthPerformance.NewOrderAmount = MonthOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                MonthPerformance.RepurchaseOrderAmount = MonthOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                MonthPerformance.GiftFrequency = MonthOrderList.Where(p=>p.TotalAmount == 19).Count();
                if (MonthPerformance.TotalFinalAmount == 0)
                {
                    MonthPerformance.MyPerformanceAmount = 0;
                }
                else
                {
                    foreach (DeliveryManage.Model.Sys_PerformanceRules rule in userRules)
                    {
                        if (rule.MinLimit <= MonthPerformance.TotalFinalAmount && rule.MaxLimit >= MonthPerformance.TotalFinalAmount)
                        {
                            MonthPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(MonthPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                            break;
                        }
                    }
                }
                monthInfo = MonthPerformance;
                #endregion
            } 
            #endregion

            #region 数据排行榜
            string where2 = string.Format("Status= 1 and RoleType!=10000", model.Id);
            string startdate2 = DateTime.Now.Year + "-" + DateTime.Now.Month + "-01";
            string enddate2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).ToString("yyyy-MM-dd");
            List<DeliveryManage.Model.Sys_User> userlist = new List<DeliveryManage.Model.Sys_User>();
            DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
            userlist = dal.GetTuiList(where2);
            List<EmployeePerformance> allPerformanceList = new List<EmployeePerformance>();
            //依次计算员工业绩
            if (userlist != null && userlist.Count > 0)
            {
                foreach (var item in userlist)
                {
                    //获取业绩提成给规则
                    List<DeliveryManage.Model.Sys_PerformanceRules> userRules = Rules.Where(p => p.ToType == (item.IsBasicSalary ? 1 : 0)).ToList();
                    DateTime firstDayOfMonth = Convert.ToDateTime(startdate2);
                    DateTime endDayOfMonth = Convert.ToDateTime(enddate2);
                    ///提交时间位于区间且审核通过的订单数据
                    string orderWhere = string.Format("EmployeeId = {0} and Status in ({1},{2}) and Created > '{3}' and Created < '{4}'", item.Id, (int)DTEnums.EnumOrderState.AuditSuccess,
                        (int)DTEnums.EnumOrderState.FinishOrder, firstDayOfMonth, endDayOfMonth);
                    List<DeliveryManage.Model.Pro_Orders> MonthOrderList = orderDal.GetAllOrderList(orderWhere);

                    //获取区间业绩数据
                    EmployeePerformance MonthPerformance = new EmployeePerformance();
                    MonthPerformance.Employee = item.Id;
                    MonthPerformance.EmployeeName = item.Nickname;
                    MonthPerformance.TotalFinalAmount = MonthOrderList.Where(p=>p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.AddOrderNum = MonthOrderList.Count();
                    MonthPerformance.EmployeeType = item.IsBasicSalary;
                    MonthPerformance.NewOrderNum = MonthOrderList.Where(p => p.OrderType == false).Count();
                    MonthPerformance.RepurchaseOrder = MonthOrderList.Where(p => p.OrderType == true).Count();
                    MonthPerformance.NewOrderAmount = MonthOrderList.Where(p => p.OrderType == false && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.RepurchaseOrderAmount = MonthOrderList.Where(p => p.OrderType == true && p.TotalAmount != 19).Sum(p => p.TotalAmount);
                    MonthPerformance.GiftFrequency = MonthOrderList.Where(p=>p.TotalAmount == 19).Count();
                    //计算业绩提成
                    if (MonthPerformance.TotalFinalAmount == 0)
                    {
                        MonthPerformance.MyPerformanceAmount = 0;
                    }
                    else
                    {
                        foreach (DeliveryManage.Model.Sys_PerformanceRules rule in userRules)
                        {
                            if (rule.MinLimit <= MonthPerformance.TotalFinalAmount && rule.MaxLimit >= MonthPerformance.TotalFinalAmount)
                            {
                                MonthPerformance.MyPerformanceAmount = (decimal)Math.Round(Convert.ToDouble(MonthPerformance.TotalFinalAmount * rule.CommRatio / 100M), 2);
                                break;
                            }
                        }
                    }
                    allPerformanceList.Add(MonthPerformance);
                }
            }
            PerformanceRanking = allPerformanceList.OrderByDescending(p=>p.TotalFinalAmount).Take(5).ToList();
            OrderRanking = allPerformanceList.OrderByDescending(p => p.AddOrderNum).Take(5).ToList();
            #endregion
            #endregion
            ViewBag.TodayPerformance = todayInfo;
            ViewBag.MonthPerformance = monthInfo;
            ViewBag.PerformanceRanking = PerformanceRanking;
            ViewBag.OrderRanking = OrderRanking;
            ViewBag.isEmployee = isEmployee;
            return View();
        }

        #endregion

        #region 修改密码
        public ActionResult PwdEdit()
        {
            DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            return View(model);
        }

        [HttpPost]
        public ActionResult NewEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                string oldpwd = collection["oldpwd"].Trim();
                string newpwd = collection["newpwd"].Trim();
                string confirmpwd = collection["confirmpwd"].Trim();
                if (model==null|| string.IsNullOrEmpty(oldpwd) || string.IsNullOrEmpty(newpwd) || string.IsNullOrEmpty(confirmpwd))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入密码！" });
                }
                #region 数据安防
                if (!PageValidate.IsSpecial(oldpwd) || !PageValidate.IsSpecial(newpwd) || !PageValidate.IsSpecial(confirmpwd))
                {
                    return Json(new ReturnMsgModel { code = 400, msg = "密码不能输入特殊字符！" });
                }
                #endregion
                if (model.Pwd != ZyEncrypter.GetMd5str(model.Name + oldpwd))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "旧密码输入有误！" });
                }
                if (newpwd != confirmpwd)
                {
                    return Json(new ReturnMsgModel { status = false, msg = "确认密码不一致！" });
                }
                confirmpwd = ZyEncrypter.GetMd5str(model.Name + confirmpwd);
                result = dal.UpdateField(model.Id, string.Format("Pwd='{0}'", confirmpwd));
                if (result)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
        }
        #endregion

        #region 邮件发送设置
        public ActionResult EmailEdit()
        {
            DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
            model = MvcApplication.UserList[model.Id];
            return View(model);
        }
        [HttpPost]
        public ActionResult EmailEdit(FormCollection collection)
        {
            try
            {
                bool result = false;
                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                DeliveryManage.DAL.Sys_User dal = new DeliveryManage.DAL.Sys_User();
                string email = collection["email"].Trim();
                string remandVal = collection["RemandVal"].Trim();
                if (model == null || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(remandVal))
                {
                    return Json(new ReturnMsgModel { status = false, msg = "请输入密码！" });
                }
                #region 数据安防
                if (!PageValidate.IsEmail(email))
                {
                    return Json(new ReturnMsgModel { code = 400, msg = "请输入有效的邮箱地址！" });
                }
                if (!PageValidate.IsIntNumber(remandVal) || int.Parse(remandVal) < 0)
                {
                    return Json(new ReturnMsgModel { code = 400, msg = "邮件提醒阈值不能小于0！" });
                }
                #endregion
                model = MvcApplication.UserList[model.Id];
                model.Email = email;
                model.RemandVal = Convert.ToInt32(remandVal);
                MvcApplication.UserList[model.Id] = model;
                result = dal.UpdateField(model.Id, string.Format("email='{0}',RemandVal={1}", email, remandVal));
                if (result)
                {
                    return Json(new ReturnMsgModel { status = true, msg = "保存成功！" });
                }
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
            }
        }
        #endregion

        #region 获取业绩排行榜数据

        [HttpPost]
        public JsonResult PostCallStatData()
        {
            return Json(new ReturnMsgModel { status = false, msg = "保存失败！" });
        }
        #endregion

        #region 获取最新开单消息
        [HttpPost]
        public JsonResult PostNewOrderMessage()
        {
            try
            {
                DeliveryManage.Model.Sys_User model = Session["session_admin_info"] as DeliveryManage.Model.Sys_User;
                if (model==null) 
                {
                    return Json(new ReturnMsgModel { status = false, msg = "暂无订单消息！" });
                }
                if (MvcApplication.UserList.ContainsKey(model.Id)) 
                {
                    int OrderId = MvcApplication.UserList[model.Id].NewOrderId;
                    if (OrderId > 0) 
                    {
                        DeliveryManage.Model.Pro_Orders _OrdersModel = new DeliveryManage.Model.Pro_Orders();
                        DeliveryManage.DAL.Pro_Orders _OrdersDAL = new DeliveryManage.DAL.Pro_Orders();
                        _OrdersModel = _OrdersDAL.GetModel(OrderId);
                        if (_OrdersModel != null)
                        {
                            if (MvcApplication.UserList.ContainsKey(_OrdersModel.EmployeeId))
                            {
                                _OrdersModel.CustomerName = MvcApplication.UserList[_OrdersModel.EmployeeId].Nickname;
                            }
                            MvcApplication.UserList[model.Id].NewOrderId = 0;//清除缓存
                                                                         
                            return Json(new ReturnMsgModel { status = true, msg = "系统提示最新订单消息！", data = _OrdersModel });
                        }
                    }
                }
               
               return Json(new ReturnMsgModel { status = false, msg = "暂无订单消息！" });
            }
            catch (Exception e)
            {
                return Json(new ReturnMsgModel { status = false, msg = "获取失败！" + e.Message });
            }
        }
        #endregion
    }
}